package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        //创建serverSocketChnnel

        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        //得到一个selector对象
        Selector selector = Selector.open();
        //服务器监听6666端口
        serverChannel.socket().bind(new InetSocketAddress(6666));

        //非阻塞模式
        serverChannel.configureBlocking(false);

        // 注册到selector中心, OP_ACCEPT
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        //等待客户端连接
        while (true){

            //等待连接
            if (selector.select(1000)==0){
                System.out.println("服务器等待了1秒了,无连接");
                continue;
            }

            //获取到有事件发生的事件集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            //遍历 selectionKeys ,使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            //开始遍历
            while (keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();
                //对每一种事件进行分析
                if (key.isAcceptable()){  //如果是OP_ACCEPT ,说明右客户端连接
                    //连接通道, 对该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverChannel.accept();

                    socketChannel.configureBlocking(false);
                    //将客户端也注册到selector上
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));



                }
                if (key.isReadable()){  //发生 OP_READ
                    //通过key 反向获取对应的channel
                    SocketChannel channel =(SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer =(ByteBuffer) key.attachment();
                    channel.read(buffer);

                    System.out.println("from 客户端"+new String(buffer.array()));
                }

                //手动从集合中移动当前的selection key
                keyIterator.remove();
            }

        }


    }
}
